<template>
  <el-form size="small" :model="searchForm" label-width="0px" class="m-t-10">
    <el-form-item class="select-date">
      <div class="flex-block">
      <el-radio-group v-model="searchForm.timeType" @change="changeTimeType">
        <el-radio-button v-for="(item,index) in initData.timeTypes" :key="index" :label="item.id">{{ item.name }}</el-radio-button>
      </el-radio-group>
      <div class="flex-block btn-control m-l-10" style="flex:1">
      <el-button class="btn-left" icon="el-icon-arrow-left" :disabled="btnDisabled.prev" @click="handleDate('prev')"></el-button>
      <el-date-picker
        v-show="searchForm.timeType == 'hour'"
        v-model="searchForm.dateTime"
        type="datetime"
        format="yyyy-MM-dd HH:mm:ss"
        value-format="yyyy-MM-dd HH:mm:ss"
        placeholder="选择日期"
        @change="getList"
        popper-class="drawer-date-range"
        :picker-options="pickerDate">
      </el-date-picker>
      <el-date-picker
        v-show="searchForm.timeType == 'day'"
        v-model="searchForm.date"
        type="date"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        placeholder="选择日期"
        @change="getList"
        :picker-options="pickerDateTime">
      </el-date-picker>
      <el-button class="btn-right" icon="el-icon-arrow-right" :disabled="btnDisabled.next" @click="handleDate('next')"></el-button>
      <el-button class="btn-play" :icon="interval.t ? 'el-icon-video-pause' : 'el-icon-video-play'" circle @click="autoPlay"></el-button>
    </div>
    </div>
    </el-form-item>
    <el-form-item>
      <el-radio-group v-model="searchForm.renderer" @change="changeType" >
        <template v-if="searchForm.timeType == 'hour'">
          <el-radio-button v-for="(item,index) in initData.timeRender" :key="index" :label="item.id">{{ item.name }}</el-radio-button>
        </template>
        <template v-else>
          <el-radio-button v-for="(item,index) in initData.dateRender" :key="index" :label="item.id">{{ item.name }}</el-radio-button>
        </template>
      </el-radio-group>
    </el-form-item>
  </el-form>
</template>
<script>
import {types,legendColors,typesRenderer,popupTemplate} from '@/views/page/live-weather/config';
import {airQualityLevesByHourOrDay,airQualityValuesByHourOrDay,airQualityColors } from '@/assets/js/config';
import {city, cityPinyin } from '@/config/env';
export default {
  data(){
    return {
      searchForm:{
        date: '',
        dateTime: '',
        renderer: 'aqi',
        timeType: 'hour'
      },
      btnDisabled:{
        prev: false,
        next: false,
      },
      initData:{
        startTime: 0,
        endTime: 23,
        dateRange: [],
        timeRange: [],
        dateRender: [
          {id: 'aqi', name: 'AQI', values: [0,50,100,150,200,300]},
          {id: 'pm25', name: 'PM₂.₅', values: [0,35,75,115,150,250]},
          {id: 'pm10', name: 'PM₁₀', values: [0,50,150,250,350,420]},
          {id: 'so2', name: 'SO₂', values: [0,50,150,475,800,1600]},
          {id: 'no2', name: 'NO₂', values: [0,40,80,180,280,565]},
          {id: 'co', name: 'CO', values: [0,2,4,35,14,24]},
          {id: 'o3_8h', name: 'O₃_8h', values: [0,100,160,215,265,800]}
        ],
        timeRender:[
          {id: 'aqi', name: 'AQI', values: [0,50,100,150,200,300]},
          {id: 'pm25', name: 'PM₂.₅', values: [0,35,75,115,150,250]},
          {id: 'pm10', name: 'PM₁₀', values: [0,50,150,250,350,420]},
          {id: 'so2', name: 'SO₂', values: [0,50,150,475,800,1600]},
          {id: 'no2', name: 'NO₂', values: [0,40,80,180,280,565]},
          {id: 'co', name: 'CO', values: [0,2,4,35,14,24]},
          {id: 'o3', name: 'O₃', values: [0,100,160,215,265,800]}
        ],
        legend: legendColors,
        timeTypes:[
          {id: 'hour', name: '时'},
          {id: 'day', name: '日'}
        ],

      },
      pickerDate:{
        disabledDate: null
      },
      pickerDateTime:{
        disabledDate: null
      },
      map: null,
      interval: {
        t: null,
        isPlay: false,
        index: 0,
        len: 0,
        current: 0,
      },
    }
  },
  created() {
    
  },
  beforeDestroy(){
    clearInterval(this.interval.t);
    this.interval.t = null;
  },
  watch:{
    'searchForm.dateTime'(newVal,oldVal){
      this.getBtnStatic();
    },
    'searchForm.date'(newVal,oldVal){
      this.getBtnStatic();
    },
  },
  methods:{
    async getInitData(){
      let dates = await this.$request('get', '/chaqi/daily_dt', {});
      let times = await this.$request('get', '/chaqi/dt', {});
      this.initData.dateRange = dates.map(item => item.dt);
      this.initData.timeRange = times.map(item => {
        return this.$moment(item).format('YYYY-MM-DD HH') +':00:00';
      });
      this.searchForm.date = this.initData.dateRange[0];
      this.searchForm.dateTime = this.initData.timeRange[0];

      this.pickerDate.disabledDate = (time)=>{
        let len = this.initData.dateRange.length;
        const current = new Date(this.initData.dateRange[0]).getTime();
        const start = new Date(this.initData.dateRange[len-1]).getTime();
        return time.getTime() > current || time.getTime() < start;
      }
      this.pickerDateTime.disabledDate = (time)=>{
        let len = this.initData.timeRange.length;
        const current = new Date(this.initData.timeRange[0]).getTime();
        const start = new Date(this.initData.timeRange[len-1]).getTime();
        return time.getTime() > current || time.getTime() < start;
      }
    },
    changeTimeType(val){
      this.searchForm.renderer = 'aqi';
      clearInterval(this.interval.t);
      this.interval.t = null;
      this.interval.current = 0;
      this.getBtnStatic();
      this.getList();
    },
    changeType(val){
      this.searchForm.renderer = val;
      this.addLayer();
    },
    getBtnStatic(){
      if(this.searchForm.timeType == 'hour'){
        let len = this.initData.dateRange.length;
        this.btnDisabled.next = this.searchForm.dateTime == this.initData.timeRange[0];
        this.btnDisabled.prev = this.searchForm.dateTime == this.initData.timeRange[len-1];
      }else{
        let len = this.initData.dateRange.length;
        this.btnDisabled.next = this.searchForm.date == this.initData.dateRange[0];
        this.btnDisabled.prev = this.searchForm.date == this.initData.dateRange[len - 1];
      }
    },
    handleDate(type){
      if(this.searchForm.timeType == 'hour'){
        let i = this.initData.timeRange.indexOf(this.searchForm.dateTime);
        if(type == 'prev'){
          this.searchForm.dateTime = this.initData.timeRange[i +1];
        }else{
          this.searchForm.dateTime = this.initData.timeRange[i -1];
        }
      }else{
        let i = this.initData.dateRange.indexOf(this.searchForm.date);
        if(type == 'prev'){
          this.searchForm.date = this.initData.dateRange[i +1];
        }else{
          this.searchForm.date = this.initData.dateRange[i -1];
        }
      }
      this.getList();
    },
    getTime(val){
      return val < 10 ? ('0'+val) : val;
    },
    autoPlay(){
      if(this.interval.t){
        clearInterval(this.interval.t);
        this.interval.t = null;
      }else{
        let dateList = [];
        if(this.searchForm.timeType == 'hour'){
          dateList = this.initData.timeRange;
        }else{
          dateList = this.initData.dateRange;
        }
        this.interval.len = dateList.length;
        this.interval.t = setInterval(() => {
          if(this.interval.len == this.interval.current){
            clearInterval(this.interval.t);
            this.interval.t = null;
            return;
          }
          this.interval.current ++;
          if(this.searchForm.timeType == 'hour'){
            this.searchForm.dateTime = dateList[this.interval.current];
          }else{
            this.searchForm.date = dateList[this.interval.current];
          }
          this.getList();

        },3000)
      }
    },
    async getList(){
      this.map = this.$parent.map;
      if(this.initData.timeRange.length == 0){
        await this.getInitData();
        this.changeTimeType('hour'); 
      }         
      let params ={};
      let url;
      if(this.searchForm.timeType == 'hour'){
        url = '/chaqi/st';
        let arrDt = this.searchForm.dateTime.split(' ')
        let arr = arrDt[0].split('-');
        let time = arrDt[1].split(':');
        params.dt_year = Number(arr[0]);
        params.dt_month = Number(arr[1]);
        params.dt_day = Number(arr[2]);
        params.dt_hour = Number(time[0]);
      }else{
        url = '/chaqi/daily';
        let arr = this.searchForm.date.split('-');
        params.dt_year = Number(arr[0]);
        params.dt_month = Number(arr[1]);
        params.dt_day = Number(arr[2]);
      }
      this.$request('get', url, params, (data,msg) => {
        this.list = data;
        this.addLayer()
      })
    },
    async addLayer(){
      if (!this.map) {
        return;
      }
      const layerId = 'air-monitor';
      if (this.map.getLayer(layerId)) {
        this.map.removeLayer(layerId);
      }
      const key = this.searchForm.renderer;
      // if (this.params.layerId !== layerId) {
      //   if (this.map.getLayer(layerId)) this.map.removeLayer(layerId);
      //   if (this.map.getSource(layerId)) this.map.removeSource(layerId);
      //   this.map.resize();
      //   return;
      // }

      const geojson = {
        type: 'FeatureCollection',
        features: [],
      };
      const data = [...this.list];
      for await (const d of data) {
        const item = d;
        item[key] = Number(item[key]);
        if (Number(item[key]) > 0) {
          geojson.features.push({
            type: 'Feature',
            geometry: {
              type: 'Point',
              coordinates: [d.lon, d.lat]
            },
            properties: d
          });
        }
      }
      if (!this.map.getSource(layerId)) {
        this.map.addSource(layerId, {
          type: 'geojson',
          data: geojson,
        });
      } else {
        (this.map.getSource(layerId)).setData(geojson);
      }
      const circleColors = [
        'step',
        ['to-number', ['get', this.searchForm.renderer]],
      ];
      const levels = this.searchForm.timeType === 'hour'
        ? airQualityLevesByHourOrDay.时 : airQualityLevesByHourOrDay.日;
      const values = this.searchForm.timeType === 'hour'
        ? airQualityValuesByHourOrDay.时 : airQualityValuesByHourOrDay.日;
      values[key].forEach((v, i) => {
        circleColors.push(airQualityColors[levels[key][i]]);
        circleColors.push(v + 0.000001);
      });
      circleColors.push(airQualityColors[levels[key][levels[key].length - 1]]);
      if (!this.map.getLayer(layerId)) {
        this.map.addLayer({
          id: layerId,
          type: 'circle',
          source: layerId,
          paint: {
            'circle-color': circleColors,
            'circle-stroke-width': 1,
            'circle-radius': 6,
            'circle-stroke-color': '#000',
          }
        }, this.map.getLayer('area-border') ? 'area-border' : undefined);
        // const addPopup = this.layers.find(i => i.id === layerId).addPopup;
        // if (addPopup) {
          this.addPopup(layerId);
        // }
      } else {
        this.map.setPaintProperty(layerId, 'circle-color', circleColors);
      }
      // 必须要加上这一句代码，否则setPaintProperty不生效
      this.map.resize();
    },
    addPopup(layerId) {
            const popup = new mapboxgl.Popup({
                closeButton: false,
                closeOnClick: false
            });
            this.map.on('mouseenter', layerId, (e) => {
                this.map.getCanvas().style.cursor = 'pointer';
                const coordinates = e.features[0].geometry.coordinates.slice();
                while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
                    coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
                }
                const prop = e.features[0].properties;
                let html = `<div class="map-popup-container">`;
                html += `<div class="popup-title">${city}空气质量</div>`;
                html += '<div class="popup-content"><table class="popup-table">';
                if (this.searchForm.timeType === 'hour') {
                    html += `<tr><td>城市</td><td>${prop.city}</td></tr>`;
                    html += `<tr><td>站点</td><td>${prop.positionname}</td></tr>`;
                    html += `<tr><td>监测时间</td><td>${prop.updatetime ? this.$moment(prop.updatetime).format('YYYY-MM-DD HH:00') : ''}</td></tr>`;
                    html += `<tr><td>空气质量</td><td>${prop.quality}</td></tr>`;
                    html += `<tr><td>首污</td><td>${prop.primarypollutant}</td></tr>`;
                    html += `<tr><td>AQI</td><td>${prop.aqi}</td></tr>`;
                    html += `<tr><td>PM₂.₅</td><td>${prop.pm25}</td></tr>`;
                    html += `<tr><td>PM₁₀</td><td>${prop.pm10}</td></tr>`;
                    html += `<tr><td>SO₂</td><td>${prop.so2}</td></tr>`;
                    html += `<tr><td>CO</td><td>${prop.co}</td></tr>`;
                    html += `<tr><td>O₃</td><td>${prop.o3}</td></tr>`;
                } else {
                    html += `<tr><td>城市</td><td>${prop.city}</td></tr>`;
                    html += `<tr><td>站点</td><td>${prop.position_name}</td></tr>`;
                    html += `<tr><td>监测时间</td><td>${prop.update_time ? this.$moment(prop.update_time).format('YYYY-MM-DD') : ''}</td></tr>`;
                    html += `<tr><td>空气质量</td><td>${prop.quality}</td></tr>`;
                    html += `<tr><td>首污</td><td>${prop.primary_pollutant}</td></tr>`;
                    html += `<tr><td>AQI</td><td>${prop.aqi}</td></tr>`;
                    html += `<tr><td>PM₂.₅</td><td>${prop.pm25}</td></tr>`;
                    html += `<tr><td>PM₁₀</td><td>${prop.pm10}</td></tr>`;
                    html += `<tr><td>SO₂</td><td>${prop.so2}</td></tr>`;
                    html += `<tr><td>CO</td><td>${prop.co}</td></tr>`;
                    html += `<tr><td>O₃_8h</td><td>${prop.o3_8h}</td></tr>`;
                }
                html += '</table></div>'
                html += '</div>';
                popup.setLngLat(coordinates)
                    .setHTML(html)
                    .addTo(this.map);
            });
            this.map.on('mouseleave', layerId, () => {
                this.map.getCanvas().style.cursor = '';
                popup.remove();
            });
        }
  },
}
</script>


